import json

import requests
from pydispatch import dispatcher
from requests.auth import HTTPDigestAuth

from logger import log
from settings import settings


def cmd(cmd: str):
    url = f"http://{settings.access_control_ip}/ISAPI/AccessControl/RemoteControl/door/1"
    auth = HTTPDigestAuth(settings.access_control_username, settings.access_control_password)
    xml = f"""<RemoteControlDoor xmlns="http://www.isapi.org/ver20/XMLSchema" version="2.0">
    <cmd>{cmd}</cmd>
</RemoteControlDoor>"""
    try:
        response = requests.put(url, data=xml, auth=auth, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
    except Exception as e:
        log.exception(e)


# 处理每个摄像头的数据
def callback(msg):
    print(f"callback msg:{msg}")
    loads = json.loads(msg)
    cmd(loads['cmd'])


def main():
    dispatcher.connect(callback, signal="access_control")


if __name__ == "__main__":
    main()
